<template>
  <div>
    <a-row type="flex" :gutter="16">
      <a-col :md="5" :sm="24">
        <a-card title="知识库" :bordered="false">
          <a-icon slot="extra" type="plus" @click.stop="handleAddCategory(null)" />
          <a-tree
            :autoExpandParent="true"
            :defaultExpandAll="true"
            :blockNode="true"
            showLine
            checkStrictly
            :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
            :treeData="categoryList"
          >
            <template slot="custom" slot-scope="item">
              <div class="box" @click.stop="handleSelect(item)">
                <span>{{ item.categoryName }}</span>
                <a-icon
                  style="margin-left: 15px"
                  v-if="item.children"
                  type="plus"
                  @click.stop="handleAddCategory(item.classId)"
                />
                <a-icon style="margin-left: 5px" type="form" @click.stop="handleEditCategory(item)" />
                <a-icon
                  style="margin-left: 5px"
                  v-if="!item.children || item.children.length == 0"
                  type="delete"
                  @click.stop="handleDelete2(item.classId)"
                />
              </div>
            </template>
          </a-tree>
          <a-modal
            :visible="deleteVisible2"
            :centered="true"
            :confirm-loading="deleteLoading2"
            @ok="handleDeleteGroup(deleteId2)"
            @cancel="handleDeleteCancel2"
            width="350px"
          >
            <span>确认删除此栏目?</span>
          </a-modal>
          <package-modal ref="packageModalForm" @ok="packageModalFormOk"></package-modal>
        </a-card>
      </a-col>
      <a-col :md="24 - 5" :sm="24">
        <a-card :bordered="false">
          <div class="it_search">
            <a-form-model :form="form" layout="inline">
              <a-row>
                <a-col style="float: left"
                  ><a-button :style="{ marginBottom: '1rem' }" type="primary" @click="handleAddContent">
                    添加文章
                  </a-button></a-col
                >
                <a-col style="float: right">
                  <a-form-model-item label="文章名称">
                    <a-input v-model="title" />
                  </a-form-model-item>
                  <a-form-model-item label="标签">
                    <a-input v-model="keywords" />
                  </a-form-model-item>
                  <a-button type="primary" @click="handleCheck">
                    查询
                  </a-button>
                </a-col>
              </a-row>
            </a-form-model>
          </div>
          <a-modal
            :visible="deleteVisible"
            :centered="true"
            :confirm-loading="deleteLoading"
            @ok="handleDeleteOk"
            @cancel="handleDeleteCancel"
            width="350px"
          >
            <span>确认删除此文章吗?</span>
          </a-modal>
          <a-table
            :pagination="ipagination"
            :loading="loading"
            rowKey="contentId"
            :bordered="true"
            :columns="listColumns"
            :data-source="list"
            @change="handleTableChange"
            :scroll="{ x: 1000 }"
          >
            <a slot="action" slot-scope="text, record">
              <a-button @click="handleView(record.contentId)">预览</a-button>
              <a-button v-if="record.topMark != 1" @click="handleToTop(record.contentId, record.classId, 1)">
                置顶
              </a-button>
              <a-button v-else @click="handleToTop(record.contentId, record.classId, 2)">
                取消置顶
              </a-button>
              <a-button @click="handleEditContent(record.contentId)">编辑</a-button>
              <a-button @click="handleDelete(record.contentId)">删除</a-button>
            </a>
            <template slot="image" slot-scope="text, record">
              <div style="display: flex; justify-content: space-around; flex-wrap: wrap;" v-if="record.image">
                <div v-for="(photo, index) in record.image.split(',')" :key="index">
                  <img style="width: 50px; height: 50px;" :src="photo" :preview="record.image.split(',')" />
                </div>
              </div>
              <div v-else></div>
            </template>
          </a-table>

          <a-modal
            title="预览"
            :visible="viewVisit"
            :confirm-loading="viewLoading"
            @cancel="viewCancel"
            destroyOnClose
            width="700px"
          >
            <p v-html="content" style="overflow:hidden"></p>
          </a-modal>

          <service-modal ref="serviceModalForm" @ok="serviceModalFormOk"></service-modal>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { getAction, postAction, deleteAction } from '@/api/manage'
import PackageModal from './modules/PackageModal'
import ServiceModal from './modules/ServiceModal'
import moment from 'moment'

const listColumns = [
  {
    title: '标题',
    dataIndex: 'title',
    align: 'center'
  },
  {
    title: '图片',
    dataIndex: 'image',
    width: 70,
    align: 'center',
    scopedSlots: { customRender: 'image' }
  },
  {
    title: '浏览量',
    dataIndex: 'view',
    width: 80,
    align: 'center'
  },
  {
    title: '标签',
    dataIndex: 'keywords',
    width: 100,
    align: 'center'
  },
  {
    title: '操作',
    key: 'operation',
    width: 350,
    fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  components: { PackageModal, ServiceModal },
  data() {
    return {
      loading: true,
      viewLoading: false,
      viewVisit: false,
      deleteVisible: false,
      deleteLoading: false,
      deleteVisible2: false,
      deleteLoading2: false,
      content: '',
      deleteId: '',
      categoryList: [],
      category: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      groupQueryUrl: 'article/category/all',
      listUrl: 'article/list',
      listParams: {
        pageNum: 1,
        pageSize: 10,
        articleCategory: 1
      },
      deleteId2: '',
      listColumns,
      list: [],
      title: '',
      keywords: '',
      form: this.$form.createForm(this),
      classId: 1
    }
  },
  watch: {
    classId() {
      this.listParams.articleCategory = this.classId
      this.listParams.pageNum = 1
    }
  },
  created() {
    this.getGroups()
    this.getList()
  },
  methods: {
    getGroups() {
      //拉取 栏目分类
      getAction(this.groupQueryUrl).then(res => {
        if (res.success) {
          this.categoryList = res.result
          this.categoryList.forEach(item => {
            this.$set(item, 'scopedSlots', { title: 'custom' })
          })
        }
      })
    },
    handleSelect(item) {
      this.classId = item.classId
      this.ipagination.current = 1
      this.getList(item)
    },
    getList(item) {
      item && (this.listParams.articleCategory = item.classId)
      console.log(this.listParams)
      this.loading = true
      postAction(this.listUrl, this.listParams)
        .then(res => {
          if (res.success) {
            this.list = res.result.records
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleCheck() {
      this.loading = true
      const listParams = {
        pageNum: 1,
        pageSize: 10,
        articleCategory: this.classId,
        title: this.title,
        keyword: this.keywords
      }
      postAction(this.listUrl, listParams)
        .then(res => {
          if (res.success) {
            this.list = res.result.records
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    viewCancel() {
      this.viewVisit = false
    },
    handleToTop(contentId, classId, topMark) {
      postAction('article/detail/manage', {
        contentId,
        classId,
        topMark
      }).then(() => {
        this.getList()
      })
    },
    handleDelete(articleId) {
      this.deleteVisible = true
      this.deleteId = articleId
    },
    handleDelete2(id) {
      this.deleteVisible2 = true
      this.deleteId2 = id
    },
    handleDeleteCancel() {
      this.deleteVisible = false
      this.deleteId = ''
    },
    handleDeleteCancel2() {
      this.deleteVisible2 = false
      this.deleteId2 = ''
    },
    handleDeleteOk() {
      this.deleteLoading = true
      getAction(`article/detail/delete/${this.deleteId}`)
        .then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
        .finally(() => {
          this.deleteLoading = false
          this.handleDeleteCancel()
        })
    },
    handleView(id) {
      postAction('article/detail', { dataId: id }).then(res => {
        if (res.success) {
          this.viewVisit = true
          this.content = res.result.content
        } else {
          console.log(res.message)
        }
      })
    },
    handleTableChange(pagination) {
      this.ipagination = pagination
      this.listParams.pageNum = pagination.current
      this.listParams.pageSize = pagination.pageSize
      this.getList()
    },
    handleAddContent() {
      this.$refs.serviceModalForm.add(this.classId)
      this.$refs.serviceModalForm.title = '添加文章'
      this.$refs.serviceModalForm.disableSubmit = false
    },
    handleEditContent(id) {
      this.$refs.serviceModalForm.edit(id)
      this.$refs.serviceModalForm.title = '编辑文章'
      this.$refs.serviceModalForm.disableSubmit = false
    },
    disabledDate(current) {
      return current < moment().subtract(1, 'day')
    },
    isRightMobileNumber(rule, value, callback) {
      if (typeof value === 'undefined' || value === '') {
        callback()
      } else {
        const regex = /^1[3456789]\d{9}$/
        if (!regex.test(value)) {
          this.isAnyWrongData = true
          callback(new Error('请输入正确手机格式'))
        } else {
          this.isAnyWrongData = false
        }
        callback()
      }
    },
    handleAddCategory(id) {
      this.$refs.packageModalForm.add(id)
      this.$refs.packageModalForm.title = '新增分类'
      this.$refs.packageModalForm.disableSubmit = false
    },
    handleEditCategory(item) {
      const record = {
        categoryName: item.categoryName,
        categoryIcon: item.categoryIcon,
        classId: item.classId,
        parentId: item.parentId,
        articleCount: item.articleCount
      }
      this.$refs.packageModalForm.edit(record)
      this.$refs.packageModalForm.title = '编辑分类'
      this.$refs.packageModalForm.disableSubmit = false
    },
    packageModalFormOk() {
      this.getGroups()
    },
    serviceModalFormOk() {
      this.getList({ classId: this.classId })
    },
    handleDeleteGroup(id) {
      getAction(`article/category/delete/${id}`).then(res => {
        if (res.success) {
          this.$message.success('删除成功')
          this.handleDeleteCancel2()
          this.getGroups(this.classId)
        } else {
          this.$message.warning(res.message)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.ant-btn {
  margin: 0.2rem;
}

.flup-item {
  margin: 1rem;
  padding: 0.5rem;
  display: flex;
  align-items: center;

  span {
    flex: 1;
  }
}

#tip {
  display: block;

  #warning {
    // margin: 0.3rem;
    text-align: right;
  }
}
.it_search {
  background: white;
  border-top-left-radius: 2px;
  border-top-right-radius: 2px;
  // padding: 10px 20px;
  color: rgba(0, 0, 0, 0.85);
}
.it_search > div {
  margin-bottom: 10px;
}
.ant-tag {
  font-size: 14px;
}
/deep/.ant-modal-body {
  max-height: 550px;
  overflow: auto;
}
/deep/.ant-collapse-header {
  text-align: center;
}
/deep/.ant-list-item {
  justify-content: center;
}
/deep/.ant-list-item:hover {
  cursor: pointer;
}
</style>

